<template>
  <div>
    <el-dialog v-model="dialogFormVisible" :title="title" width="800" destroy-on-close :close-on-click-modal="closeOnClickModal">
      <el-form ref="formRef" :model="form" :rules="rules">
        <el-form-item label="优惠券名称" prop="couponName" :label-width="formLabelWidth">
          <el-input v-model="form.couponName" autocomplete="off" placeholder="请输入优惠券名称" clearable />
        </el-form-item>
        <el-form-item label="优惠券类型" prop="couponType" :label-width="formLabelWidth">
          <el-radio-group v-model="form.couponType">
            <el-radio value="0" size="large">通用券</el-radio>
            <el-radio value="1" size="large">商品券</el-radio>
            <el-radio value="2" size="large">品类券</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="优惠券面值" prop="couponParValue" :label-width="formLabelWidth">
          <el-input-number v-model="form.couponParValue" :min="1" />
        </el-form-item>
        <el-form-item label="使用门槛" prop="useThreshold" :label-width="formLabelWidth">
          <el-radio-group v-model="form.useThreshold" @change="handleUseThreshold">
            <el-radio value="0" size="large">无门槛</el-radio>
            <el-radio value="1" size="large">有门槛</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.useThreshold === '1'" label="优惠券最低消费" prop="minimumConsumption" :label-width="formLabelWidth">
          <el-input-number v-model="form.minimumConsumption" :min="1"  />
        </el-form-item>
        <el-form-item label="使用有效期" prop="useExpirationDate" :label-width="formLabelWidth">
          <el-radio-group v-model="form.useExpirationDate">
            <el-radio value="0" size="large">天数</el-radio>
            <el-radio value="1" size="large">时间段</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.useExpirationDate === '0'" label="使用有效期限（天）" prop="expirationDay" :label-width="formLabelWidth">
          <el-input-number v-model="form.expirationDay" :min="0" />
        </el-form-item>
        <el-form-item v-if="form.useExpirationDate === '1'" label="使用有效期限" prop="expirationTimeSlot" :label-width="formLabelWidth">
          <el-date-picker
            v-model="form.expirationTimeSlot"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :size="size"
            :disabled-date="disabledDate"
            format="YYYY-MM-DD hh:mm:ss"
            value-format="YYYY-MM-DD hh:mm:ss"
            @change="expirationTimeSlotChange"
          />
        </el-form-item>
        <el-form-item label="领取是否限时" prop="receiveExpirationType" :label-width="formLabelWidth">
          <el-radio-group v-model="form.receiveExpirationType">
            <el-radio value="0" size="large">限时</el-radio>
            <el-radio value="1" size="large">不限时</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.receiveExpirationType === '0'" label="领取时间" prop="receiveExpiration" :label-width="formLabelWidth">
          <el-date-picker
            v-model="form.receiveExpiration"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :size="size"
            :disabled-date="disabledDate"
            format="YYYY-MM-DD hh:mm:ss"
            value-format="YYYY-MM-DD hh:mm:ss"
            placement="top"
            @change="receiveExpirationChange"
          />
        </el-form-item>
        <el-form-item label="领取方式" prop="receiveType" :label-width="formLabelWidth">
          <el-radio-group v-model="form.receiveType">
            <el-radio value="0" size="large">手动领取</el-radio>
            <el-radio value="1" size="large">新人券</el-radio>
            <el-radio value="2" size="large">赠送券</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否限量" prop="isLimitType" :label-width="formLabelWidth">
          <el-radio-group v-model="form.isLimitType">
            <el-radio value="0" size="large">限量</el-radio>
            <el-radio value="1" size="large">不限量</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.isLimitType === '0'" label="发布数量" prop="limitNum" :label-width="formLabelWidth">
          <el-input-number v-model="form.limitNum" :min="1" />
        </el-form-item>
        <el-form-item label="排序" prop="sort" :label-width="formLabelWidth">
          <el-input-number v-model="form.sort" :min="1" />
        </el-form-item>
        <el-form-item label="状态" prop="couponStatus" :label-width="formLabelWidth">
          <el-radio-group v-model="form.couponStatus">
            <el-radio value="0" size="large">开启</el-radio>
            <el-radio value="1" size="large">关闭</el-radio>
          </el-radio-group>
          <div v-if="form.couponStatus === '0'" style="color: red;margin-left: 20px;">
            <span>一旦开启，将无法修改，请谨慎开启!</span>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSure">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
  import { reactive, ref } from 'vue'
  import { ElMessageBox } from 'element-plus'
  import { showMessage } from '~/utils/my-notification'
  import { saveOrUpdate, getCouponInfo } from '~/api/coupon/coupon'

  const emit = defineEmits(['refreshDataList'])
  
  const formRef = ref(null)
  const dialogFormVisible = ref(false)
  const formLabelWidth = '150px'
  const title = ref('新建优惠券')
  const closeOnClickModal = ref(false)
  const size = ref('default')

  const form = reactive({
    id: 0,
    couponName: '',
    couponType: '0',
    couponParValue: '',
    useThreshold: '0',
    minimumConsumption: '',
    useExpirationDate: '0',
    expirationDay: '',
    expirationTimeSlotStart: '',
    expirationTimeSlotEnd: '',
    receiveExpirationType: '1',
    receiveExpirationStart: '',
    receiveExpirationEnd: '',
    receiveType: '1',
    isLimitType: '1',
    limitNum: '',
    sort: 0,
    couponStatus: '1',
    expirationTimeSlot: [],
    receiveExpiration: []
  })
  const rules = {
    couponName: [
      { required: true, message: '优惠券名称不能为空!', trigger: 'blur' },
    ],
    conponParValue: [
      { required: true, message: '优惠券面值不能为空!', trigger: 'blur' },
    ],
    expirationDay: [
      { required: true, message: '使用有效期限（天）不能为空!', trigger: 'blur' },
    ],
    minimumConsumption: [
      { required: true, message: '优惠最低消费不能为空!', trigger: 'blur' },
    ],
    limitNum: [
      { required: true, message: '发布数量不能为空!', trigger: 'blur' },
    ]
  }

  // 初始化
  function init(id) {
    dialogFormVisible.value = true
    form.id = 0
    form.couponName = ''
    form.couponType = '0'
    form.couponParValue = ''
    form.useThreshold = '0'
    form.minimumConsumption = ''
    form.useExpirationDate = '0'
    form.expirationDay = ''
    form.expirationTimeSlotStart = ''
    form.expirationTimeSlotEnd = ''
    form.receiveExpirationType = '1'
    form.receiveExpirationStart = ''
    form.receiveExpirationEnd = ''
    form.receiveType = '1'
    form.isLimitType = '1'
    form.limitNum = ''
    form.sort = 0
    form.couponStatus = '1'
    form.expirationTimeSlot = []
    form.receiveExpiration = []
    if(id) {
      // 修改
      // 查询详情
      getCouponInfo(id).then(res => {
        if(res && res.data.code === 200) {
          const data = res.data.data
          form.id = data.id
          form.couponName = data.couponName
          form.couponType = data.couponType + ''
          form.couponParValue = data.couponParValue
          form.useThreshold = data.useThreshold + ''
          form.minimumConsumption = data.minimumConsumption
          form.useExpirationDate = data.useExpirationDate + ''
          if(data.useExpirationDate === 0) {
            form.expirationDay = data.expirationDay
          } else {
            form.expirationTimeSlotStart = data.expirationTimeSlotStart
            form.expirationTimeSlotEnd = data.expirationTimeSlotEnd
            form.expirationTimeSlot = [data.expirationTimeSlotStart, data.expirationTimeSlotEnd]
          }
          form.receiveExpirationType = data.receiveExpirationType + ''
          if(data.receiveExpirationType === 0) {
            form.receiveExpirationStart = data.receiveExpirationStart
            form.receiveExpirationEnd = data.receiveExpirationEnd
            form.receiveExpiration = [data.receiveExpirationStart, data.receiveExpirationEnd]
          }
          form.receiveType = data.receiveType + ''
          form.isLimitType = data.isLimitType + ''
          form.limitNum = data.limitNum
          form.sort = data.sort
          form.couponStatus = data.couponStatus + ''
        }
      })
    }
  }
  // 使用门槛值改变时
  function handleUseThreshold(val) {
    
  }
  function disabledDate(time) {
    // 禁用今天之前的日期
    const today = new Date();
    today.setHours(0, 0, 0, 0); // 将时间设置为午夜，避免时分秒的影响
    return time.getTime() < today.getTime();
  }
  // 使用有效期
  function expirationTimeSlotChange(val) {
    form.expirationTimeSlotStart = val[0]
    form.expirationTimeSlotEnd = val[1]
  }
  // 领取时间
  function receiveExpirationChange(val) {
    form.receiveExpirationStart = val[0]
    form.receiveExpirationEnd = val[1]
  }
  // 确认按钮
  function handleSure() {
    formRef.value.validate((valid) => {
      if(!valid) {
        return false
      }
      ElMessageBox.confirm(`确定进行保存操作?`, '提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal: false
      }).then(() => {
        saveOrUpdate(form).then(res => {
          if(res && res.data.code === 200) {
            dialogFormVisible.value = false
            emit('refreshDataList')
          } else {
            showMessage(res.data.message, 'error')
          }
        })
      }).catch(err => {
        console.log(err)
      })
    })
  }

  // 将方法暴露给父组件
  defineExpose({
    init
  })
</script>
<style>

</style>